# from audioop import reverse

from django import http
from django.conf import settings
from django.contrib.auth import login
from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse
from django.views import View
from QQLoginTool.QQtool import OAuthQQ
# 1.获取登陆url
from apps.ausers.models import User
# from django.contrib.auth.models import User
from apps.oauth.models import OAuthQQUser
from meiduo_mall.settings.dev import logger
from utils.response_code import RETCODE
from utils.secret import SecretOauth
def is_bind_openid(request, openid,next):
    try:
        oauth_user = OAuthQQUser.objects.get(openid=openid)
    except Exception as e:
        logger.error(e)
        # 2. 未绑定了－－－－跳转到　绑定的页面
        #加密
        data_dict = {"openid":openid}
        secret_openid = SecretOauth().dumps(data_dict)
        context = {"openid":secret_openid}
        return render(request,"oauth_callback.html",context)
    else:
        # 1.绑定－－保持登录状态－－－设置username--cookie---跳转到首页
        user = oauth_user.user
        #保持登录状态
        login(request,user)
        #设置username--cookie
        if next:
            response = redirect(next)
        else:
            response = redirect(reverse("contents:index"))
        # new_url = reverse("contents:index")
        # response = redirect(new_url)
        #--跳转到首页
        response.set_cookie("username",user.username,max_age=3600*24*14)
        return response

class QQAuthUserView(View):
    def get(self, request):
        code = request.GET.get("code")
        next = request.GET.get("state")
        if not code:
            return http.HttpResponseForbidden("缺少code")
        from QQLoginTool.QQtool import OAuthQQ
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,client_secret=settings.QQ_CLIENT_SECRET, redirect_uri=settings.QQ_REDIRECT_URI,state=next)
        # code---token
        try:
            access_token = oauth.get_access_token(code)
            # token--openid
            openid = oauth.get_open_id(access_token)
        except Exception as e:
            logger.error(e)
            return http.HttpResponseServerError("Oauth2.0认证失败！")
        #判断是否绑定了openid
        response = is_bind_openid(request,openid,next)
        # 返回前端
        return response
    def post(self,request):
        #1.接收参数 request.POST
        mobile = request.POST.get('mobile')
        pwd = request.POST.get('password')
        sms_code_client = request.POST.get('sms_code')
        openid = request.POST.get('openid')
        # 2.解析参数 校验 判空 正则
        # 3.校验短信 1.redis取出来2.redis_sms_code.decode()
        #校验openid 有还是没有
        #解密
        openid = SecretOauth().loads(openid).get("openid",None)
        if not openid:
            return render(request,"oauth_callback.html",{"openid_errmsg":"无效的openid"})
        # 4.判断用户是否存在mobile = mobile
        try:
            user = User.objects.get(mobile=mobile)
        except Exception as e:
            logger.error(e)
            #    不存在  新建了
            user = User.objects.create_user(username=mobile, password=pwd,mobile=mobile)
        else:
    # 如果存在check_password()
            if not user.check_password(pwd):
                return render(request,"oauth_callback.html",{"account_errmsg":"用户名或密码错误"})
        # 5.openid 和user绑定== 新建一条记录
        try:
            OAuthQQUser.objects.create(openid=openid,user=user)
        except Exception as e:
            logger.error(e)
            return render(request,"oauth_callback.html",{"qq_login_errmsg":"QQ登录失败"})
        # 6.login()-set_cookie重定向的首页
        login(request,user)

        next = request.GET.get("state")
        if next:
            response = redirect(next)
        else:
            response = redirect(reverse("contents:index"))

        response.set_cookie("username",user.username)

        return response
class QQAuthURLView(View):
    # def get(self, request):
    #     next = request.GET.get("next")
    #     # 1.实例化　qq认证　类
    #     oauth_qq = OAuthQQ(
    #         client_secret=settings.QQ_CLIENT_SECRET,
    #         client_id=settings.QQ_CLIENT_ID,
    #         redirect_uri=settings.QQ_REDIRECT_URI,
    #         state = next
    #     )
    #     # 2. 获取登陆网址
    #     login_url = oauth_qq.get_qq_url()
    #     # 3. 返回给前端
    #     return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'login_url':login_url})
    #     pass

    def get(self, request):
        next = request.GET.get('next')
        # 1.实例化 qq认证类
        from QQLoginTool.QQtool import OAuthQQ
        oauth_qq = OAuthQQ(
            client_secret=settings.QQ_CLIENT_SECRET,
            client_id=settings.QQ_CLIENT_ID,
            redirect_uri=settings.QQ_REDIRECT_URI,
            state=next
        )

        # 2.获取登录网址
        login_url = oauth_qq.get_qq_url()

        # 3.返回给前端
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'login_url': login_url})























